<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列  expand设置展开 -->
        <el-table-column type="expand">
            <template slot-scope="scope">
                <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bdbottom',i1===0?'bdtop':'','center']" >
                    <!-- 一级权限渲染 -->
                    <el-col :span="9">
                      <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 二级和三级权限渲染 -->
                    <el-col :span="15">
                      <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2===0?'':'bdtop','center']" >
                        <!-- 二级权限渲染 -->
                        <el-col :span="6">
                          <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                          <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 三级权限渲染 -->
                        <el-col :span="18">
                          <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                        </el-col>
                      </el-row>
                    </el-col>
                </el-row>
            </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <!-- 分配权限 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 权限分配弹框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="resetKey">
    <!-- 树形结构 -->
    <el-tree :data="rightsList" :props="treeProps" show-checkbox  node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
    <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
   </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      // 控制权限弹框数值
      setRightDialogVisible: false,
      // 用来存储权限列表数据
      rightsList: [],
      // 树的规则数据
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      // 存储的角色id 用来当做请求参数
      roleId: ''
    }
  },
  // 钩子
  created() {
    this.getRolesList()
  },
  methods: {
    //   权限角色列表获取
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) { return this.$message.error('获取权限列表失败') }
      this.$message.success('获取角色权限列表成功')
      this.rolesList = res.data
    },
    // 删除权限标签
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // 删除请求
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限标签失败')
      this.$message.success('删除权限标签成功')
      console.log(res)
      // 防止页面重新刷新 增加用户体验
      role.children = res.data
    },
    // 权限分配显示
    async showSetRightDialog(role) {
      this.roleId = role.id
      this.setRightDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      // this.$message.success('获取权限列表成功')
      this.rightsList = res.data
      // 调用递归
      this.getLeafKeys(role, this.defKeys)
    },
    // 通过递归获取三级节点的id
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 在 权限对话框中 增加关闭事件
    resetKey() {
      this.defKeys = []
    },
    // 权限的分配
    async allotRights() {
      const keys = [
        // 全选id
        ...this.$refs.treeRef.getCheckedKeys(),
        // 半选id
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 拼接字符串
      const idStr = keys.join(',')
      // 发起添加权限请求
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('角色授权失败')
      this.$message.success('角色授权成功')
      // 关闭弹框
      this.setRightDialogVisible = false
      // 重新获取数据
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .center {
    display: flex;
    align-items: center;
  }
</style>
